package org.tooyoung.fourone.map;


import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.squareup.picasso.Picasso;

import org.tooyoung.fourone.BaseFragment;
import org.tooyoung.fourone.R;
import org.tooyoung.fourone.chat.AddOrContactActivity;
import org.tooyoung.fourone.live.activitys.PlayActivity;
import org.tooyoung.fourone.live.models.CPIgetData;
import org.tooyoung.fourone.live.models.MapAsyncTask;
import org.tooyoung.fourone.live.models.Room;
import org.tooyoung.fourone.user.activity.LoginActivity;
import org.tooyoung.fourone.user.model.UserImformation;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Random;

/**
 * A simple {@link Fragment} subclass.
 */
public class MapFragment extends BaseFragment implements BDLocationListener, BaiduMap.OnMarkerClickListener, BaiduMap.OnMapClickListener, OnGetGeoCoderResultListener, MapAsyncTask.Cpi {


    private View ret;
    private MapView mMapView;
    private LocationClient mLocationClient;
    private BaiduMap mBaiduMap;
    private Marker mSelfMarker;
    private LayoutInflater mLayoutInflater;
    private InfoWindow mInfoWindow;
    private BMapManager mapManager;
    private GeoCoder mSearch;
    private Queue<Room> mRoomQueue;

    private static final String TAG = "MapFragment";
    public MapFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        SDKInitializer.initialize(getActivity().getApplicationContext());
        ret = inflater.inflate(R.layout.fragment_map, container, false);
        mLayoutInflater = LayoutInflater.from(this.getContext());
        mRoomQueue=new LinkedList<>();

        mMapView = (MapView) ret.findViewById(R.id.bmapView);
        //获取核心
        mBaiduMap = mMapView.getMap();


        mMapView.removeViewAt(1); // 去掉百度logo
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        mBaiduMap.setMyLocationEnabled(true);
        mBaiduMap.setOnMapClickListener(this);
        mBaiduMap.setOnMarkerClickListener(this);


        initLocationClient();

        List<Room> rooms = CPIgetData.getList();
        //Log.d(TAG, "rooms: "+rooms);
        if (rooms != null) {
            new MapAsyncTask(this,rooms).execute();
        }




//        if (rooms != null) {
//            for (int i = 0; i < rooms.size(); i++) {
//                Room room = rooms.get(i);
//                String city = room.getCity();
//                if (city != null) {
//                    initCitySearch(city,city);
//                    mRoomQueue.add(room);
//                }
//
//                Log.d(TAG, "onCreateView: "+city);
//            }
//        }else{
//            Log.d(TAG, "onCreateView: room为空");
//        }


        List<UserImformation> users = LoginActivity.getUserInformation();
        setUserMark(users);

        return ret;
    }



    private void initCitySearch(String city,String address){

        //创建地理编码检索实例
        GeoCoder search = GeoCoder.newInstance();
        search.setOnGetGeoCodeResultListener(this);

        search.geocode(new GeoCodeOption()
                .city(city)
                .address(address)
        );
        //search.destroy();
        search=null;
    }

    private void initLocationClient() {
        // 初始化定位
        mLocationClient = new LocationClient(getContext());

        // 设置定位参数
        LocationClientOption option = new LocationClientOption();

        // 1. 设置定位的精度
        // 高精度
        // 省电模式
        // GPS
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        // 2. 设置定位的时间间隔, 单位 ms, < 1000 代表只定位一次
        option.setScanSpan(5000);
        // 3. 定位的结果的类型, 针对百度地图,或者高德、或者其他
        option.setCoorType("bd09ll"); // bd09ll 代表百度地图, gcj02
        // 4. 打开GPS
        option.setOpenGps(true);
        // 5. 是否接收地址信息
        option.setIsNeedAddress(true);
        // 6. 设置
        mLocationClient.setLocOption(option);

        // 7. 设置定位结果接口回调
        mLocationClient.registerLocationListener(this);

        // 针对定位, 自定进行定位的请求
       mLocationClient.start();
    }

    @Override
    public void onResume() {
        mMapView.onResume();
        super.onResume();
    }

    @Override
    public void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    public String getTitle() {
        return "地图";
    }

    @Override
    public void onDestroyView() {
        //在onPause 取消定位操作
        mLocationClient.unRegisterLocationListener(this);
        //mSearch.destroy();
        mMapView.onDestroy();
        mSelfMarker = null;
        super.onDestroyView();
    }


    @Override
    public void onReceiveLocation(BDLocation bdLocation) {
        // 定位接口可能返回错误码,要根据结果错误码,来判断是否是正确的地址;

        int locType = bdLocation.getLocType();


        switch (locType){
            case BDLocation.TypeGpsLocation:
            case BDLocation.TypeCacheLocation:
            case BDLocation.TypeNetWorkLocation:
            case BDLocation.TypeOffLineLocation:

                double latitude = bdLocation.getLatitude();
                double longitude = bdLocation.getLongitude();
                LatLng point = new LatLng(latitude, longitude);

                // 始终保证当前位置是屏幕的中心
               // MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(point);
                //mBaiduMap.setMapStatus(update);

                // TODO: 添加/移动 Marker对象
                if(mSelfMarker == null){
                    MarkerOptions options = new MarkerOptions();
                    options.position(point);
                    BitmapDescriptor descriptor =
                            BitmapDescriptorFactory.fromAsset("Icon_start.png");
                    options.icon(descriptor);



                    mSelfMarker = (Marker) mBaiduMap.addOverlay(options);
                }
                // 如果已经创建过 Marker,那么更新位置
                mSelfMarker.setPosition(point);
                break;

        }
    }

    private void setMark(LatLng point,int type,Bundle bundle) {
          // TODO: 添加/移动 Marker对象



              if(type == 1){

                  MarkerOptions options = new MarkerOptions();
                  options.position(point);
                  BitmapDescriptor descriptor =
                          BitmapDescriptorFactory.fromAsset("Icon_end.png");
                  options.icon(descriptor);


                  // 可以给Marker添加附加信息,在点击的时候,实现特定的参数获取;
                  bundle.putInt("type",type);
                  options.extraInfo(bundle);

                  mBaiduMap.addOverlay(options);

              } else if(type==2){

                View markView = mLayoutInflater.inflate(R.layout.custom_foot_marker, null);
                Room room = bundle.getParcelable("room");
                ImageView imgView= (ImageView) markView.findViewById(R.id.img_pic);
                imgView.setImageResource(R.mipmap.ghost);
                Bitmap bitmap = BMapUtil.getBitmapFromView(markView);

                MarkerOptions options = new MarkerOptions();
                options.position(point);
                BitmapDescriptor descriptor = BitmapDescriptorFactory.fromBitmap(bitmap);
                //BitmapDescriptor descriptor =
                  //        BitmapDescriptorFactory.fromAsset("Icon_start.png");
                  options.icon(descriptor);


                  // 可以给Marker添加附加信息,在点击的时候,实现特定的参数获取;
                  bundle.putInt("type",type);
                  options.extraInfo(bundle);

                  mBaiduMap.addOverlay(options);

              }


    }

    private void setUserMark(List<UserImformation> users){

        LatLng pt1 = new LatLng(39.93923, 116.357428);
        LatLng pt2 = new LatLng(39.91923, 116.327428);
        LatLng pt3 = new LatLng(39.89923, 116.347428);
        LatLng pt4 = new LatLng(39.89923, 116.367428);
        LatLng pt5 = new LatLng(39.91923, 116.387428);

        LatLng pt6 = new LatLng(39.93723, 116.357528);
        LatLng pt7 = new LatLng(39.91823, 116.327428);
        LatLng pt8 = new LatLng(39.89923, 116.347228);
        LatLng pt9 = new LatLng(39.89123, 116.367128);
        LatLng pt10 = new LatLng(39.91223, 116.387328);

        List<LatLng> pts = new ArrayList<LatLng>();
        pts.add(pt1);
        pts.add(pt2);
        pts.add(pt3);
        pts.add(pt4);
        pts.add(pt5);

        pts.add(pt6);
        pts.add(pt7);
        pts.add(pt8);
        pts.add(pt9);
        pts.add(pt10);

        if (users != null) {
            for (int i = 0; i < users.size(); i++) {

                Random random = new Random();
                int j = random.nextInt(9);

                UserImformation user = users.get(i);
                Bundle bundle=new Bundle();
                bundle.putParcelable("user",user);
                setMark(pts.get(j),1,bundle);
            }
        }
    }



    @Override
    public boolean onMarkerClick(Marker marker) {

        LatLng position = marker.getPosition();
        //Toast.makeText(getContext(), "位置:" + position, Toast.LENGTH_SHORT).show();
        showInfoWindow(marker);

        return true;
    }


    private void showInfoWindow(final Marker marker) {  //显示气泡
        // 创建InfoWindow展示的view


        double latitude, longitude;
        latitude = marker.getPosition().latitude;
        longitude = marker.getPosition().longitude;
        LatLng pt = new LatLng(latitude, longitude );

        Bundle bundle = marker.getExtraInfo();

        int type = bundle.getInt("type");


        View view=null;
        if(type==1){
            view = LayoutInflater.from(getContext()).inflate(R.layout.map_infowindow, null); //自定义气泡形状
            TextView nameTxt= (TextView) view.findViewById(R.id.infowindow_name);
            TextView sexTxt= (TextView) view.findViewById(R.id.infowindow_sex);
            UserImformation user= bundle.getParcelable("user");

            nameTxt.setText("昵称："+user.getUsername());
            sexTxt.setText("性别："+user.getSex());

            view.setTag(user);

        }else if(type==2){

            view = LayoutInflater.from(getContext()).inflate(R.layout.live_infowin, null); //自定义气泡形状
            ImageView imgeView = (ImageView) view.findViewById(R.id.infowin_live_img);
            TextView nameTxt= (TextView) view.findViewById(R.id.infowin_live_name);
            TextView cityTxt= (TextView) view.findViewById(R.id.infowin_live_city);
            Room room = bundle.getParcelable("room");

            view.setTag(room);

            if(room!=null){
                Picasso.with(getContext())
                        .load(room.getHeadimg())
                        .resize(320,300)
                        .config(Bitmap.Config.ARGB_8888)
                        .into(imgeView);
                nameTxt.setText(room.getNickname());
                String city=room.getCity();
                if (city != null) {
                    cityTxt.setText(city);
                }
            }
        }


        if (view != null) {
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Object tag = v.getTag();
                    if (tag instanceof Room) {
                        Room room= (Room)tag;
                        Intent intent = new Intent(getContext(), PlayActivity.class);
                        intent.putExtra("data",room);
                        getContext().startActivity(intent);

                        //Toast.makeText(getContext(), room.getNickname(), Toast.LENGTH_SHORT).show();

                    }else if(tag instanceof  UserImformation){
//                        Toast.makeText(getContext(), "点击了用户窗口", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(getContext(), AddOrContactActivity.class);
                        intent.putExtra("user" , ((UserImformation) tag).getUsername());
                        Log.d(TAG, "user: " + ((UserImformation) tag).getUsername());
                        startActivity(intent);
                    }
                }
            });

            // 创建InfoWindow
            //创建InfoWindow , 传入 view， 地理坐标， y 轴偏移量
            mInfoWindow = new InfoWindow(view,pt,-80);
            mBaiduMap.showInfoWindow(mInfoWindow); //显示气泡
        }
    }

    @Override
    public void onMapClick(LatLng latLng) {
        mBaiduMap.hideInfoWindow();//影藏气泡
    }

    @Override
    public boolean onMapPoiClick(MapPoi mapPoi) {
        return false;
    }

    @Override
    public void onGetGeoCodeResult(GeoCodeResult result) {
        if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
            //没有检索到结果
            //Toast.makeText(getContext(), "没有检索到结果", Toast.LENGTH_LONG).show();
            mRoomQueue.poll();
        }else{
            //获取地理编码结果
            LatLng location = result.getLocation();
            Room room = mRoomQueue.poll();
            Bundle bundle = new Bundle();
            bundle.putParcelable("room",room);

            setMark(location,2,bundle);

            //Toast.makeText(getContext(), location.toString(), Toast.LENGTH_LONG).show();
        }

    }

    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {

    }


    @Override
    public void send(List<Room> data) {
        //Log.d(TAG, "dataList: "+data);

        for (int i = 0; i < data.size(); i++) {
            Room room = data.get(i);
            String lat = room.getLat();
            String lng = room.getLng();
            LatLng latLng = new LatLng(Double.parseDouble(lat),Double.parseDouble(lng));

            Bundle bundle = new Bundle();
            bundle.putParcelable("room",room);

            setMark(latLng,2,bundle);
        }
    }
}